<template>
	<el-dialog title="选择人员" :visible.sync="visible" append-to-body top="0" width="992px" custom-class="sw_select_user">
		<div class="query_user_wrapper" v-loading="tableLoading">
			<el-form size="mini" inline>
				<el-form-item><el-input v-model="queryData.account" clearable placeholder="用户账号" style="width: 180px"></el-input></el-form-item>
				<el-form-item><el-input v-model="queryData.userName" clearable placeholder="用户姓名" style="width: 180px"></el-input></el-form-item>
				<el-form-item>
					<el-select v-model="queryData.type" clearable placeholder="用户类型" style="width: 100px">
						<el-option v-for="(item, index) in dictEnums['USER_TYPE']" :key="index" :label="item.msg" :value="item.value"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-select v-model="queryData.sex" clearable placeholder="用户性别" style="width: 100px">
						<el-option v-for="(item, index) in dictEnums['USER_SEX']" :key="index" :label="item.msg" :value="item.value"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item><el-button type="primary" @click="queryTableData()">查询</el-button></el-form-item>
			</el-form>
			<el-table v-bind="tableConfig" :data="tableData" @row-click="handleRowClick" @select="handleSelectTable" @select-all="handleAllSelectTable">
				<el-table-column type="selection" width="48" align="center"></el-table-column>
				<el-table-column prop="account" label="用户账号" width="200" show-overflow-tooltip />
				<el-table-column prop="userName" label="用户姓名" width="140"></el-table-column>
				<el-table-column prop="deptName" label="用户性别" width="80">
					<template slot-scope="{ row }">
						<dict-tag dict="USER_SEX" :data="row.sex"></dict-tag>
					</template>
				</el-table-column>
				<el-table-column prop="deptName" label="用户部门" width="200" show-overflow-tooltip />
				<el-table-column prop="type" label="用户类型" width="80">
					<template slot-scope="{ row }">
						<dict-tag dict="USER_TYPE" :data="row.type"></dict-tag>
					</template>
				</el-table-column>
			</el-table>
			<sw-pagination
				:layout="userPageLayout"
				:total="dataCount"
				:page.sync="queryData.page"
				:limit.sync="queryData.limit"
				@change="queryTableData()"
			></sw-pagination>
		</div>
		<div class="select_user_wrapper">
			<div class="list">
				<div class="item" v-for="(item, index) in checkedUser" :key="index">
					<el-avatar size="medium" shape="square" :src="item.picPath | picPathFilter(siteInfo)"></el-avatar>
					<h4>{{ item.relName }}</h4>
					<el-button size="medium" type="text" icon="el-icon-delete" @click="handleDeleteUser(item)"></el-button>
				</div>
			</div>
			<div class="button">
				<el-button size="small" @click="visible = false">取消</el-button>
				<el-button size="small" type="primary" :loading="loading" @click="handleSubmitUser">确定</el-button>
			</div>
		</div>
	</el-dialog>
</template>

<script>
import lodash from 'lodash';
import { mapGetters } from 'vuex';
import { getUserList } from '@/api/system/tbSysUser';
export default {
	enums: ['USER_TYPE'],
	props: {
		value: { type: Boolean, default: false },
		data: { type: Array, default: () => [] },
		loading: { type: Boolean, default: false }
	},
	data() {
		return {
			visible: this.value,
			tableLoading: false,
			userPageLayout: 'slot, prev, pager, next',
			squareUrl: require('@/assets/img/avatar_image.png'),
			tableConfig: { ref: 'table', rowKey: 'id', height: '100%', size: 'medium' },
			dataCount: 0,
			queryData: {},
			tableData: [],
			checkedUser: [],
			originalChecked: []
		};
	},
	computed: {
		...mapGetters(['siteInfo'])
	},
	filters: {
		picPathFilter(input, data) {
			if (!!input) {
				return window.staticPath + input;
			} else if (!!data.userPicPath) {
				return window.staticPath + data.userPicPath;
			} else {
				return require('@/assets/img/avatar_image.png');
			}
		}
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		async visible(flag) {
			this.$emit('input', flag);
			if (!flag) return false;
			this.queryData = { page: 1, limit: 15 };
			this.queryTableData();
		},
		data(arr) {
			this.checkedUser = [...arr];
			console.log(arr);
			this.originalChecked = lodash.cloneDeep(arr);
		},
		tableData(arr) {
			let users = this.checkedUser;
			this.$refs['table'].clearSelection();
			arr.forEach((item) => {
				if (!users.some((n) => n.relId === item.id)) return false;
				this.$nextTick(() => {
					this.$refs['table'].toggleRowSelection(item, true);
				});
			});
		}
	},
	methods: {
		//获取用户列表数据
		async getTableData() {
			let params = { ...this.queryData };
			let result = await getUserList(params).then((res) => res.data);
			this.tableLoading = false;
			if (result.code === '0') {
				this.dataCount = parseInt(result.count);
				this.tableData = !result.data ? [] : result.data;
			}
		},

		//查询用户列表数据
		queryTableData() {
			this.tableLoading = true;
			this.getTableData();
		},

		//行点击事件
		handleRowClick(data, column) {
			if (column.property === 'selection') return false;
			if (this.checkedUser.some((n) => n.relId === data.id)) {
				let index = this.checkedUser.findIndex((n) => n.relId === data.id);
				this.$refs['table'].toggleRowSelection(data, false);
				this.checkedUser.splice(index, 1);
			} else {
				this.checkedUser.push({ relId: data.id, relName: data.userName, picPath: data.picPath });
				this.$refs['table'].toggleRowSelection(data, true);
			}
		},

		//点击选中
		handleSelectTable(selection, data) {
			if (this.checkedUser.some((n) => n.relId === data.id)) {
				let index = this.checkedUser.findIndex((n) => n.relId === data.id);
				this.checkedUser.splice(index, 1);
			} else {
				this.checkedUser.push({ relId: data.id, relName: data.userName, picPath: data.picPath });
			}
		},

		//全选用户
		handleAllSelectTable(selection) {
			if (selection.length > 0) {
				selection.forEach((item) => {
					if (this.checkedUser.some((n) => n.relId === item.id)) return false;
					this.checkedUser.push({ relId: item.id, relName: item.userName, picPath: item.picPath });
				});
			} else {
				this.tableData.forEach((item) => {
					let index = this.checkedUser.findIndex((n) => n.relId === item.id);
					this.checkedUser.splice(index, 1);
				});
			}
		},

		//删除选中用户
		handleDeleteUser(data) {
			let index = this.checkedUser.findIndex((n) => n.relId === data.relId);
			this.checkedUser.splice(index, 1);
			if (this.tableData.some((n) => n.id === data.relId)) {
				let info = this.tableData.find((n) => n.id === data.relId);
				!!info && this.$refs['table'].toggleRowSelection(info, false);
			}
		},

		//提交选中用户
		async handleSubmitUser() {
			let addArr = this.checkedUser.filter((n) => !this.originalChecked.some((k) => k.relId === n.relId));
			let delArr = this.originalChecked.filter((n) => !this.checkedUser.some((k) => k.relId === n.relId));
			let exports = [...addArr.map((n) => ({ ...n, oper: 'add' })), ...delArr.map((n) => ({ ...n, oper: 'del' }))];
			this.$emit('submit', exports, this.checkedUser);
		}
	}
};
</script>
<style lang="scss">
.sw_select_user .el-dialog__body {
	display: flex;
	padding: 0;
}
</style>
<style lang="scss" scoped>
.query_user_wrapper::v-deep {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 201px);
	overflow: hidden;
	flex: 1;
	.el-form {
		padding: 10px;
		.el-input {
			display: flex;
		}
	}
	.el-form-item {
		margin-bottom: 0;
	}
	.el-form-item__content {
		display: flex;
		align-items: center;
	}
	.el-table {
		border-top: solid 1px #ebeef5;
	}
	.el-table__row {
		cursor: pointer;
	}
	.sw-pagination {
		padding: 12px;
		margin-top: 0;
	}
}

.select_user_wrapper {
	display: flex;
	flex-direction: column;
	width: 240px;
	flex-shrink: 0;
	border-left: solid 1px #ebeef5;
	.list {
		flex: 1;
		padding: 4px 0;
		overflow: auto;
		border-bottom: solid 1px #ebeef5;
	}
	.item {
		display: flex;
		align-items: center;
		padding: 6px 10px;
		.el-avatar {
			flex-shrink: 0;
		}
		h4 {
			flex: 1;
			font-size: 14px;
			line-height: 18px;
			margin: 0 10px;
			overflow: hidden;
		}
		.el-button {
			flex-shrink: 0;
		}
	}
	.button {
		padding: 10px;
		text-align: right;
	}
}
</style>
